package com.jushu.storbox.adapter;

import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.callback.IUploadCallback;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.entities.ControlInfo;
import com.jushu.storbox.entities.UploadObject;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.manager.UploadTaskManager;
import com.jushu.storbox.operation.group.BasicItemOperation;
import com.jushu.storbox.task.tqueue.UploadTask;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.huawei.sharedrive.sdk.android.modelV2.response.FileInfoResponseV2;

public class UploadTranslateAdapter extends
		ListDisplayResolveAdapter<UploadObject,  BasicItemOperation<UploadObject> > {
	
	Context context;
	
	public UploadTranslateAdapter(Context context, List<UploadObject> datasList) {
		super(datasList);
		this.context = context;
	}

	@Override
	public View getView(int position, View contentView, ViewGroup parent) {
		ViewItemHolder viewHolder = null;
		if(contentView == null) {
			viewHolder = new ViewItemHolder();
			contentView = viewHolder.inflateFromXML(parent);
			contentView.setTag(viewHolder);
		} else {
			viewHolder = (ViewItemHolder) contentView.getTag();
		}
		
		viewHolder.initContentData(position, getItem(position));
		
		return contentView;
	}

	public class ViewItemHolder {
		private UploadObject mItemData;

		private View contentView;
		private ImageView typeImg;
		private ImageView operationImg;
		private ProgressBar translateProgress;

		private TextView itemName;
		private TextView itemSize;
		private TextView itemState;

		private View operationView;
		private View deleteView;

		private String iconPath;

		private Bitmap catchBmp;

		public ViewItemHolder() {
		}

		public View inflateFromXML(ViewGroup parent) {
			contentView = LayoutInflater.from(context).inflate(R.layout.action_translate_list_item, parent, false);
			// show info
			typeImg = (ImageView) contentView.findViewById(R.id.item_type_img);
			itemName = (TextView) contentView.findViewById(R.id.item_name_text);
			itemSize = (TextView) contentView.findViewById(R.id.item_date_text);
			itemState = (TextView) contentView.findViewById(R.id.item_filelist_file_size);
			// translate progress
			translateProgress = (ProgressBar) contentView.findViewById(R.id.translate_item_progress);
			translateProgress.setMax(100);
			// control icon
			operationView = contentView.findViewById(R.id.operation_clickable);
			operationImg = (ImageView) contentView.findViewById(R.id.item_operation_item_img);
			deleteView = contentView.findViewById(R.id.delete_clickable);
			return contentView;
		}

		public void initContentData(int position, UploadObject itemData) {
			this.rebindController(itemData);

			typeImg.setImageResource(getTypeImgeID(itemData.getName()));
			itemName.setText(itemData.getName());
			itemSize.setText(PublicTools.changeBKM(String.valueOf(itemData.getSize())));
			itemState.setText(itemData.getCurrentPaogress()+"%");
			translateProgress.setProgress((int) itemData.getCurrentPaogress());

			updateItemExtendsInfo();
			
			// binding listener
			deleteView.setOnClickListener(new OnClickListener() {
				public void onClick(View arg0) {
					getController().cancelTranslateTask();
				}
			});
			operationView.setOnClickListener(new OnClickListener() {
				public void onClick(View arg0) {
					changeTaskState();
				}
			});
		}

		private UploadController getController() {
			return (UploadController) mItemData.getControlInfo();
		}
		
		private int getTypeImgeID(String ItemName) {
			// LogUtil.i(TAG, "getTypeImgeID...");
			int typeImgResId = R.mipmap.default_file_icon;
			if (PublicTools.isFileType(ItemName, Constant.WORD_TYPE)) {
				typeImgResId = R.mipmap.doc;
			} else if (PublicTools.isFileType(ItemName, Constant.PPT_TYPE)) {
				typeImgResId = R.mipmap.ppt;
			} else if (PublicTools.isFileType(ItemName, Constant.IMAGE_TYPE)) {
				typeImgResId = R.mipmap.empty_pic;
				try {
					iconPath = mItemData.getLoctPath();
					Message msg_download = new Message();
					msg_download.what = MessageCode.REQUEST_THUMBNAIL_INLOCAL;
					handler.sendMessage(msg_download);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (PublicTools.isFileType(ItemName, Constant.RAR_TYPE)) {
				typeImgResId = R.mipmap.rar;
			} else if (PublicTools.isFileType(ItemName, Constant.ZIP_TYPE)) {
				typeImgResId = R.mipmap.rar;
			} else if (PublicTools.isFileType(ItemName, Constant.VIDEO_TYPE)) {
				typeImgResId = R.mipmap.video;
			} else if (PublicTools.isFileType(ItemName, Constant.MUSIC_TYPE)) {
				typeImgResId = R.mipmap.music;
			} else if (PublicTools.isFileType(ItemName, Constant.TXT_TYPE)) {
				typeImgResId = R.mipmap.txt;
			} else if (PublicTools.isFileType(ItemName, Constant.PDF_TYPE)) {
				typeImgResId = R.mipmap.pdf;
			} else if (PublicTools.isFileType(ItemName, Constant.EXCEL_TYPE)) {
				typeImgResId = R.mipmap.excel;
			} else {
				typeImgResId = R.mipmap.default_file_icon;
			}
			return typeImgResId;
		}

		private void rebindController(UploadObject itemData) {
			UploadController tempControl = null;
			if (mItemData != null) {
				tempControl = (UploadController) mItemData.getControlInfo();
				if(tempControl != null) {
					tempControl.setViewHolder(null);
				}
			}
			mItemData = itemData;
			if (mItemData != null) {
				tempControl = (UploadController) mItemData.getControlInfo();
				if(tempControl == null) {
					tempControl = new UploadController();
				}
				tempControl.setViewHolder(this);
				mItemData.setControlInfo(tempControl);
			}
		}

		private void updateItemExtendsInfo() {
			switch(mItemData.getTransStatus()) {
			case Constant.TRANSLATE_IS_NOTHING:
				translateProgress.setProgress(getProgress());
				operationImg.setImageResource(R.mipmap.ic_stat_play);
				itemState.setText("");
				break;
			case Constant.TRANSLATE_IS_WAITING:
				translateProgress.setProgress(getProgress());
				operationImg.setImageResource(R.mipmap.ic_stat_pause);
				itemState.setText(R.string.translate_task_waitting);
				break;
			case Constant.TRANSLATE_IS_STARTED:
				translateProgress.setProgress(getProgress());
				operationImg.setImageResource(R.mipmap.ic_stat_pause);
				itemState.setText(getProgress()+"%");
				break;
			case Constant.TRANSLATE_IS_RUNNING:
				translateProgress.setProgress(getProgress());
				operationImg.setImageResource(R.mipmap.ic_stat_pause);
				itemState.setText(getProgress()+"%");
				break;
			case Constant.TRANSLATE_IS_STOPED:
				translateProgress.setProgress(getProgress());
				operationImg.setImageResource(R.mipmap.ic_stat_play);
				itemState.setText(R.string.translate_task_stoped);
				break;
			case Constant.TRANSLATE_IS_CANCELED:
				handler.sendEmptyMessage(UiConstant.ITEM_DELETE_EXTENDS_VIEW);
				break;
			case Constant.TRANSLATE_IS_FAILURED:
				translateProgress.setProgress(getProgress());
				operationImg.setImageResource(R.mipmap.ic_stat_retry);
				itemState.setText(R.string.translate_task_failure);
				break;
			case Constant.TRANSLATE_IS_SUCCESS:
				translateProgress.setProgress(100);
				operationImg.setImageResource(R.mipmap.ic_stat_pause);
				itemState.setText(R.string.translate_task_success);
				handler.sendEmptyMessage(UiConstant.ITEM_DELETE_EXTENDS_VIEW);
				break;
			default:
				LogUtil.e(TAG, "error translate state");
			}
		}
		
		public void changeTaskState() {
			UploadController controller = getController();
			switch(mItemData.getTransStatus()) {
			case Constant.TRANSLATE_IS_NOTHING:
				controller.startTranslateTask();
				break;
			case Constant.TRANSLATE_IS_WAITING:
				controller.stopTranslateTask();
				break;
			case Constant.TRANSLATE_IS_STARTED:
				controller.stopTranslateTask();
				break;
			case Constant.TRANSLATE_IS_RUNNING:
				controller.stopTranslateTask();
				break;
			case Constant.TRANSLATE_IS_STOPED:
				controller.startTranslateTask();
				break;
			case Constant.TRANSLATE_IS_CANCELED:
				break;
			case Constant.TRANSLATE_IS_FAILURED:
				controller.startTranslateTask();
				break;
			case Constant.TRANSLATE_IS_SUCCESS:
				break;
			default:
				LogUtil.e(TAG, "error translate state");
			}
		}

		private int getProgress() {
			return (int) mItemData.getCurrentPaogress();
		}
		
		private ClientExceptionRelateHandler handler = new ClientExceptionRelateHandler() {

			@Override
			public Context getContext() {
				return context;
			}

			public void handleMessage(final Message msg) {
				switch (msg.what) {
				case UiConstant.ITEM_UPDATA_EXTENDS_VIEW:
					updateItemExtendsInfo();
					break;
					
				case UiConstant.ITEM_DELETE_EXTENDS_VIEW:
					removeData(mItemData);
					break;
				
				case MessageCode.REQUEST_THUMBNAIL_INLOCAL:
					new Thread(new Runnable() {
						public void run() {
							try {
								LogUtil.i(TAG, "thumb path: " + iconPath);
								Bitmap bmp = BitmapFactory.decodeFile(iconPath);
								ShareDriveApplication.getInstance().addCloudBitmaps(bmp);
								Message message = new Message();
								message.what = UiConstant.UPDATE_TYPE_ICON;
								message.obj = bmp;
								handler.sendMessage(message);
							} catch(Exception e) {
								
							}
						}
					}).start();
					break;

				case UiConstant.UPDATE_TYPE_ICON:// refresh image ui
					Bitmap bmp = (Bitmap) msg.obj;
					Bitmap drop = catchBmp;
					if (null != bmp) {
						catchBmp = bmp;
						typeImg.setImageBitmap(bmp);
					} else {
						LogUtil.e(TAG, "bitmap is null, show default img...");
						typeImg.setImageResource(R.mipmap.empty_pic);
					}
					if (drop != null && !drop.isRecycled()) {
						drop.recycle();
					}
					break;

				default:
					super.handleMessage(msg);
				}
			}
		};
	}
	
	class UploadController extends ControlInfo {
		ViewItemHolder viewHolder = null;
		
		UploadTask uploadTask = null;
		
		public void setViewHolder(ViewItemHolder viewHolder) {
			this.viewHolder = viewHolder;
			
			if(viewHolder != null) {
				uploadTask = UploadTaskManager.getTask(viewHolder.mItemData);
				
				if(uploadTask != null) {
					uploadTask.setCallback(callback);
				} else {
					LogUtil.e(TAG, "current task not include in downloadTaskManager!");
				}
			} else {
				LogUtil.e(TAG, "viewHolder is null instance!");
			}
		}

		public void stopTranslateTask() {
			if(viewHolder != null) {
				UploadTaskManager.stopTask(context, viewHolder.mItemData);
			} else {
				LogUtil.e(TAG, "viewHolder is null instance!");
			}
		}

		public void startTranslateTask() {
			if(viewHolder != null) {
				UploadTaskManager.startTask(context, viewHolder.mItemData);
			} else {
				LogUtil.e(TAG, "viewHolder is null instance!");
			}
		}

		@Override
		public void notifyChange() {
			if(viewHolder != null) {
				viewHolder.handler.sendEmptyMessage(UiConstant.ITEM_UPDATA_EXTENDS_VIEW);
			}
		}

		public void cancelTranslateTask() {
			if(viewHolder != null) {
				UploadTaskManager.cancelTask(context, viewHolder.mItemData);
				viewHolder.handler.sendEmptyMessage(UiConstant.ITEM_DELETE_EXTENDS_VIEW);
			} else {
				LogUtil.e(TAG, "viewHolder is null instance!");
			}
		}
		
		IUploadCallback callback = new IUploadCallback() {

			@Override
			public void onStart() {
				notifyChange();
			}

			@Override
			public void onFailure(Throwable t) {
				notifyChange();
			}

			@Override
			public void onSuccess(FileInfoResponseV2 successItem) {
				notifyChange();
				if(viewHolder != null) {
					viewHolder.handler.sendEmptyMessage(UiConstant.ITEM_DELETE_EXTENDS_VIEW);
				}
			}

			@Override
			public void onProgress(int currentProgress, long currentSize,
					long maxSize) {
				notifyChange();
			}

			@Override
			public void onStop() {
				notifyChange();
			}

			@Override
			public void onCanceled() {
				notifyChange();
				if(viewHolder != null) {
					viewHolder.handler.sendEmptyMessage(UiConstant.ITEM_DELETE_EXTENDS_VIEW);
				}
			}

			@Override
			public void onDettach() {
				notifyChange();
			}
			
		};
	}
}
